package com.fire.util.base;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * Token工具类
 * 
 * @author: zoujp
 * @date: 2018年5月27日
 */
@Component
public class TokenUtil {
	private static final String KEY_SECRET = "go_fire_key_secret";

	private static final String ISSUER = "z_sign";

	private static final String SUBJECT = "all_user";

	/**
	 * 创建JWT
	 * 
	 * @param userId
	 *            用户id
	 * @param expireTime
	 *            token过期时间,13位时间戳
	 * @return
	 * @throws IllegalArgumentException
	 * @throws UnsupportedEncodingException
	 */
	public static String createJwt(Integer userId, Long expireTime)
			throws IllegalArgumentException, UnsupportedEncodingException {
		// 加盐加密签名
		Algorithm algorithm = Algorithm.HMAC256(KEY_SECRET);
		// 生成token
		String token = JWT.create().withIssuer(ISSUER).withSubject(SUBJECT).withClaim("userId", userId)
				.withExpiresAt(new Date(expireTime)).sign(algorithm);

		return token;

	}

	/**
	 * 验证jwt
	 * 
	 * @param token
	 */
	public DecodedJWT verifyJwt(String token) throws JWTVerificationException {
		DecodedJWT jwt = null;
		try {
			// 加盐加密签名
			Algorithm algorithm = Algorithm.HMAC256(KEY_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			// 获取Payload负载
			jwt = verifier.verify(token);

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return jwt;
	}

	public static void main(String[] args) throws IllegalArgumentException, UnsupportedEncodingException {
		String token = createJwt(1, 3600000l);
		TokenUtil tokenUtil = new TokenUtil();
		try {
			tokenUtil.verifyJwt(token);
		} catch (JWTVerificationException e) {
			e.printStackTrace();
			System.out.println("验证失败");
		}
	}

}
